﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace Northwind.NET.FE.Forms
{

    public partial class EmployeesForm : Form
    {
        // Data source to build list of employees reporting to.
        Northwind.NET.FE.Datasets.DataModelDataSetTableAdapters.EmployeeTableAdapter _employeeTableAdapter =
            new Northwind.NET.FE.Datasets.DataModelDataSetTableAdapters.EmployeeTableAdapter();
        Northwind.NET.FE.Datasets.DataModelDataSet.EmployeeDataTable _employeeDataTable =
            new Northwind.NET.FE.Datasets.DataModelDataSet.EmployeeDataTable();

        private string _imagePath = String.Empty;

        public EmployeesForm()
        {
            InitializeComponent();
            _imagePath = Northwind.NET.Utilities.Context.ExecutingAssemblyFolderName + @"Pictures";
            this.firstNameTextBox.TextChanged += new EventHandler(FillFullNameTitleBar);
            this.lastNameTextBox.TextChanged += new EventHandler(FillFullNameTitleBar);
        }

        private void EmployeesForm_Load(object sender, EventArgs e)
        {
            this.employeeTableAdapter.Fill(this.dataModelDataSet.Employee);
            // Initially fill reportsToComboBox and display current value.
            LoadReportsToFullList();
            FillReportsToComboBox(null, null);
        }

        private void EmployeesForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            // Uncomment if this form is opened from main switchboard.
            //Northwind.NET.FE.Globals.Navigator.UnhideMainSwitchboard();
        }

        private void LoadReportsToFullList()
        {
            _employeeDataTable = employeeTableAdapter.GetData();
        }

        private void employeeBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.employeeBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.dataModelDataSet);
            // Requery list of possible employees to report to.
            LoadReportsToFullList();
            FillReportsToComboBox(null, null);
        }

        private void pictureTextBox_TextChanged(object sender, EventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            string fileName = textBox.Text;
            bool hasPicture = Convert.ToBoolean(fileName.Length);
            if (hasPicture == false)
            {
                // No picture.
                this.imagePictureBox.Image = null;
            }
            else
            {
                // Retrieve picture.
                string fullPath = Path.Combine(_imagePath, fileName);
                this.imagePictureBox.Load(fullPath);
            }
            this.removePictureButton.Enabled = hasPicture;
        }

        private void FillFullNameTitleBar(object sender, EventArgs e)
        {
            // Set full name in title bar.
            this.fullNameTextBox.Text = this.firstNameTextBox.Text + " " + this.lastNameTextBox.Text;
        }

        private void FillReportsToComboBox(Object sender,EventArgs e)
        {
            TextBox idTextBox = (TextBox)this.tabPage1.Controls["idTextBox"];
            ComboBox reportsToComboBox = (ComboBox)this.tabPage1.Controls["reportsToComboBox"];
            int idCurrent = -1;
            string idText = idTextBox.Text;
            if (idText.Length > 0)
            {
                idCurrent = Convert.ToInt32(idText);
            }
            // Select and order the names that can be reported to.
            // Every employee must report to someone else or none. 
            // Circular references, however, are allowed.
            string filterExpression = "ID <> " + idCurrent.ToString();
            string sortExpression = "FirstName asc, LastName asc";
            DataRow[] reportsToList = _employeeDataTable.Select(filterExpression, sortExpression);
            // Update the field Photo - which we do not use in the combobox - to 
            // hold the concatenated full name.
            foreach (DataRow dataRow in reportsToList)
            {
                dataRow.SetField("Photo", dataRow["FirstName"].ToString() + ' ' + dataRow["LastName"].ToString());
            }
            // Fill the combobox. This will select the first item.
            reportsToComboBox.DataSource = reportsToList;
            reportsToComboBox.DisplayMember = "Photo";
            reportsToComboBox.ValueMember = "ID";

            // Restore selected value.
            string reportsTo = this.reportsToTextBox.Text;
            if (reportsTo.Length == 0)
            {
                reportsToComboBox.Text = null;
            }
            else
            {
                reportsToComboBox.SelectedValue = Convert.ToInt32(reportsTo);
            }
        }

        private void employeeBindingSource_PositionChanged(object sender, EventArgs e)
        {
            FillReportsToComboBox(null, null);
        }

        private bool SelectPictureFile()
        {
            string path = _imagePath;
            string file = this.pictureTextBox.Text;
            // Reset file dialogue to always open at InitialDirectory.
            this.openFileDialog1.Reset();
            this.openFileDialog1.InitialDirectory = path;
            this.openFileDialog1.FileName = file;
            this.openFileDialog1.Title = "Select picture";
            //this.openFileDialog1.AutoUpgradeEnabled = true;
            this.openFileDialog1.Filter = @"All files (*.*)|*.*";
            this.openFileDialog1.Multiselect = false;
            //this.openFileDialog1.ValidateNames = true;
            this.openFileDialog1.RestoreDirectory = true;
            DialogResult result = this.openFileDialog1.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                try
                {
                    file = this.openFileDialog1.SafeFileName;
                    if (this.openFileDialog1.FileName.Equals(Path.Combine(path, file)))
                    {
                        this.pictureTextBox.Text = file;
                        return true;
                    }
                    else
                    {
                        MessageBox.Show("Pictures can only be selected from the folder " + path + ".", "Wrong folder", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                catch
                {
                    MessageBox.Show("The file " + file + " can not be read.", "Error when retrieving file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.pictureTextBox.Text = null;
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        private void openPictureButton_Click(object sender, EventArgs e)
        {
            SelectPictureFile();
        }

        private void removePictureButton_Click(object sender, EventArgs e)
        {
            DialogResult result;
            // Confirm removal of the picture.
            result = MessageBox.Show(
                (string)"Remove picture of this employee?",
                (string)"Removal of picture",
                MessageBoxButtons.OKCancel,
                MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2);
            if (result.Equals(DialogResult.OK))
            {
                this.pictureTextBox.Text = null;
            }
        }

    }
}
